<template>
  <div class="position-detail">
    <el-card class="position-card">
      <!-- 头部信息 -->
      <div slot="header" class="card-header" v-if="positionData">
        <h2 class="position-title">{{ positionData.current.positionName }}</h2>
        <PositionStatusTag
          :status="positionData.status"
          :failed-message="positionData.failedMessage"
          class="status-tag"
        />
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-loading-spinner size="large"></el-loading-spinner>
        <p>加载中...</p>
      </div>

      <div
        v-if="positionData && !loading && !loadFailed"
        class="content-wrapper"
      >
        <div v-if="!showUpdate">
          <div class="base-info">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">职位类型：</span>
                <span class="value">{{
                  positionData.current.positionType || "未知"
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">薪资范围：</span>
                <span class="value"
                  >{{ positionData.current.lowestSalaryMonth }}-{{
                    positionData.current.highestSalaryMonth
                  }}元/月</span
                >
              </div>
              <div class="info-item">
                <span class="label">学历要求：</span>
                <span class="value">{{
                  mapEducation(positionData.current.education)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">发布时间：</span>
                <span class="value">{{
                  formatDate(positionData.current.startAt)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">截止时间：</span>
                <span class="value">{{
                  formatDate(positionData.current.endAt)
                }}</span>
              </div>
              <!-- 发布人信息 -->
              <div class="info-item" v-if="positionData.userInfo">
                <span class="label">发布人：</span>
                <span class="value">{{ positionData.userInfo.name }}</span>
              </div>
            </div>
          </div>

          <!-- 职位详情和要求 -->
          <div class="detail-cards">
            <!-- 职位详情 -->
            <el-card class="detail-card">
              <div slot="header" class="detail-header">
                <h3 class="detail-title">职位详情</h3>
              </div>
              <div class="detail-content">
                <p>{{ positionData.current.positionDetail || "暂无详情" }}</p>
              </div>
            </el-card>

            <!-- 职位要求 -->
            <el-card class="detail-card">
              <div slot="header" class="detail-header">
                <h3 class="detail-title">职位要求</h3>
              </div>
              <div class="detail-content">
                <p>{{ positionData.current.positionRequire || "暂无需求" }}</p>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 数据变更对比 -->
        <div v-if="showUpdate" class="comparison-section">
          <el-divider content="数据变更对比" />
          <div class="change对比">
            <div class="data-card old-data">
              <h4>修改前</h4>
              <p>职位名称：{{ positionData.old?.positionName || "无" }}</p>
              <p>职位类型：{{ positionData.old?.positionType || "无" }}</p>
              <p>
                薪资范围：{{ positionData.old?.lowestSalaryMonth || 0 }}-{{
                  positionData.old?.highestSalaryMonth || 0
                }}元/月
              </p>
              <p>学历要求：{{ mapEducation(positionData.old?.education) }}</p>
              <p>发布时间：{{ formatDate(positionData.old?.startAt) }}</p>
              <p>截止时间：{{ formatDate(positionData.old?.endAt) }}</p>
              <p>职位要求：{{ positionData.old?.positionRequire || "无" }}</p>
              <p>职位详情：{{ positionData.old?.positionDetail || "无" }}</p>
            </div>
            <div class="data-card new-data">
              <h4>修改后</h4>
              <p>职位名称：{{ positionData.current?.positionName || "无" }}</p>
              <p>职位类型：{{ positionData.current?.positionType || "无" }}</p>
              <p>
                薪资范围：{{ positionData.current?.lowestSalaryMonth || 0 }}-{{
                  positionData.current?.highestSalaryMonth || 0
                }}元/月
              </p>
              <p>
                学历要求：{{ mapEducation(positionData.current?.education) }}
              </p>
              <p>发布时间：{{ formatDate(positionData.current?.startAt) }}</p>
              <p>截止时间：{{ formatDate(positionData.current?.endAt) }}</p>
              <p>
                职位要求：{{ positionData.current?.positionRequire || "无" }}
              </p>
              <p>
                职位详情：{{ positionData.current?.positionDetail || "无" }}
              </p>
            </div>
          </div>
        </div>

        <!-- 审核失败原因 -->
        <div v-if="positionData.failedMessage" class="failed-section">
          <el-divider content="审核失败原因" />
          <div class="failed-content">
            <div class="failed-text">
              <p>审核失败:{{ positionData.failedMessage }}</p>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <template v-if="fromPersonList">
            <el-button
              type="primary"
              @click="handleEdit"
              class="btn-edit"
              size="small"
            >
              <i class="el-icon-edit mr-1"></i>编辑
            </el-button>
            <el-button
              type="danger"
              @click="handleDelete"
              class="btn-delete"
              size="small"
            >
              <i class="el-icon-delete mr-1"></i>删除
            </el-button>
            <el-button @click="$router.go(-1)" class="btn-back">
              返回<i class="el-icon-arrow-right mr-1"></i>
            </el-button>
          </template>

          <!-- 从公司发布列表跳转 -->
          <template v-if="fromCompanyList">
            <template v-if="positionData?.status === 'VERIFY_COMPANY_REVIEW'">
              <el-button
                type="success"
                @click="handleApprove"
                class="btn-approve"
                size="small"
              >
                通过
              </el-button>
              <el-button
                type="danger"
                @click="handleReject"
                class="btn-reject"
                size="small"
              >
                不通过
              </el-button>
            </template>
            <el-button @click="$router.go(-1)" class="btn-back">
              返回<i class="el-icon-arrow-right mr-1"></i>
            </el-button>
          </template>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { isPendingStatus, isFailedStatus } from "@/util/positionStatus";
import PositionStatusTag from "@/views/CompanyViews/company-position/component/PositionStatusTag.vue";
import {
  getUserPublishPositionByCode,
  getUserPositionById,
  deletePosition,
  cancelPublishPosition,
  cancelUpdateUserPosition,
  companyVerifyPublishPosition,
  companyVerifyChangePosition,
  companyVerifyPublishPositionFailed,
  companyVerifyChangePositionFailed,
  checkPositionChangeInformation,
} from "@/api/recuriter/position";

export default {
  components: { PositionStatusTag },
  props: {
    id: { type: String, required: true },
    scene: { type: String, default: "code" },
    status: { type: String, default: "NORMAL" },
  },
  data() {
    return {
      positionData: null,
      loading: false,
      loadFailed: false,
    };
  },
  computed: {
    fromPersonList() {
      return this.$route.query.from === "person-position-list";
    },
    fromCompanyList() {
      return this.$route.query.from === "admin-position-list";
    },
    showUpdate() {
      return (
        this.positionData.scene === "positionId" &&
        (isPendingStatus(this.positionData.status, this.positionData.scene) ||
          isFailedStatus(this.positionData.status, this.positionData.scene))
      );
    },
  },
  created() {
    console.log(this.id);
    this.loadDetail();
  },
  methods: {
    async loadDetail() {
      this.loading = true;
      this.loadFailed = false;
      try {
        let res;
        if (this.scene === "code") {
          res = await getUserPublishPositionByCode(this.id);
        } else if (this.scene === "positionId" && this.status === "NORMAL") {
          res = await getUserPositionById(this.id);
        } else {
          res = await checkPositionChangeInformation(this.id);
        }
        this.positionData = res.data[0];
      } catch (error) {
        console.error("加载详情失败：", error);
        this.$message.error("加载详情失败，请重试");
        this.loadFailed = true;
        this.positionData = null;
      } finally {
        this.loading = false;
      }
    },
    // 编辑职位
    handleEdit() {
      this.$router.replace({
        name: "edit-posting",
        params: {
          id: this.id,
          scene: this.scene,
          mode: this.status,
          isEdit: true,
        },
      });
    },

    // 删除职位
    async handleDelete(id) {
      this.$confirm(`确定要删除该职位吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const isPending = isPendingStatus(this.status, this.scene);
            const isPendingFail = isFailedStatus(this.status, this.scene);
            if (
              (isPending && this.scene === "code") ||
              (isPendingFail && this.scene === "code")
            ) {
              const isPendingres = await cancelPublishPosition(this.id);
              this.$store.commit("recruiter/SET_TOKEN", isPendingres.data.data);
            } else if (
              this.scene === "positionId" &&
              this.status === "NORMAL"
            ) {
              const deleteres = await deletePosition(this.id);
              this.$store.commit("recruiter/SET_TOKEN", deleteres.data.data);
            } else {
              const isUpdateres = await cancelUpdateUserPosition(this.id);
              this.$store.commit("recruiter/SET_TOKEN", isUpdateres.data.data);
            }
            this.$message.success("删除成功");
            this.$router.replace({ name: "person-position-list" });
          } catch (error) {
            this.$message.error(error.response?.data?.msg || "删除失败");
          }
        })
        .catch(() => {
          console.log("删除失败");
        });
    },
    // 管理员审核通过
    async handleApprove() {
      let id = this.id;

      try {
        if (this.scene === "positionId") {
          const updateres = await companyVerifyChangePosition(id);
          this.$store.commit("recruiter/SET_TOKEN", updateres.data.data);
        } else {
          const initialres = await companyVerifyPublishPosition(id);
          this.$store.commit("recruiter/SET_TOKEN", initialres.data.data);
        }

        this.$message.success("审核已通过");
        this.$router.replace({ name: "admin-position-list" });
      } catch (error) {
        this.$message.error("审核失败，请重试");
      }
    },

    async handleReject() {
      let id = this.id;
      this.$prompt("请输入拒绝原因", "审核拒绝", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^.{1,100}$/,
        inputErrorMessage: "拒绝原因长度在1-100个字符之间",
      })
        .then(async ({ value }) => {
          try {
            if (this.scene === "positionId") {
              const updateres = await companyVerifyChangePositionFailed(
                id,
                value
              );
              this.$store.commit("recruiter/SET_TOKEN", updateres.data.data);
            } else {
              const initialres = await companyVerifyPublishPositionFailed(
                id,
                value
              );
              this.$store.commit("recruiter/SET_TOKEN", initialres.data.data);
            }
            this.$message.success("已拒绝该职位");
            this.$router.replace({ name: "admin-position-list" });
          } catch (error) {
            this.$message.error("操作失败，请重试");
          }
        })
        .catch(() => {
          console.log("已取消拒绝");
        });
    },
    formatDate(cellValue) {
      if (!cellValue) return "-";
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    mapEducation(code) {
      const map = {
        COLLEGE: "大专",
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        OTHER: "其他",
      };
      return map[code] || code;
    },
  },
};
</script>

<style scoped>
.position-detail {
  padding: 20px;
  background-color: #f9fafb;
  min-height: 100vh;
  box-sizing: border-box;
}

.position-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
}

.position-card:hover {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.position-title {
  font-size: 22px;
  font-weight: 600;
  color: #1d2129;
  margin: 0;
  flex: 1;
}

.status-tag {
  margin-left: 16px;
}

.loading-state,
.error-state {
  padding: 60px 0;
  text-align: center;
}

.loading-state p {
  margin-top: 16px;
  color: #86909c;
}

.content-wrapper {
  padding: 24px;
}

/* 基础信息样式 */
.base-info {
  margin-bottom: 30px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.info-item {
  padding: 12px 16px;
  background-color: #fafafa;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.info-item:hover {
  background-color: #f5f5f5;
  transform: translateY(-2px);
}

.label {
  display: inline-block;
  width: 90px;
  color: #86909c;
  font-weight: 500;
  font-size: 14px;
}

.value {
  color: #1d2129;
  font-size: 14px;
  line-height: 1.6;
}

/* 详情卡片样式 */
.detail-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.detail-card {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.detail-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.detail-header {
  padding: 16px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.detail-title {
  margin: 0;
  font-size: 16px;
  color: #1d2129;
  font-weight: 600;
}

.detail-content {
  padding: 20px;
}

.detail-content p {
  margin: 0;
  color: #4e5969;
  line-height: 1.8;
  font-size: 14px;
  white-space: pre-line;
}

/* 变更对比样式 */
.comparison-section {
  margin: 30px 0;
}

.change对比 {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 16px;
}

.data-card {
  padding: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.data-card h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
}

.data-card p {
  margin: 0 0 12px 0;
  color: #4e5969;
  font-size: 14px;
  line-height: 1.6;
}

.old-data {
  background-color: #fff5f5;
  border: 1px solid #ffe3e3;
}

.old-data h4 {
  color: #f53f3f;
}

.new-data {
  background-color: #f6ffed;
  border: 1px solid #e1f3d8;
}

.new-data h4 {
  color: #00b42a;
}

/* 审核失败区域 */
.failed-section {
  margin: 30px 0;
  animation: fadeIn 0.3s ease-out;
}

.failed-content {
  padding: 20px;
  background-color: #fff5f5;
  border-radius: 8px;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 2px 8px rgba(245, 63, 63, 0.1);
  transition: all 0.2s ease;
}

.failed-content:hover {
  box-shadow: 0 4px 12px rgba(245, 63, 63, 0.15);
  transform: translateY(-1px);
}

.failed-text {
  flex-grow: 1;
}

.failed-text p {
  margin: 0 0 12px 0;
  line-height: 1.7;
  font-size: 14px;
}

.failed-actions {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #ffe3e3;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: end;
  gap: 8px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.btn-back {
  background-color: #f2f3f5;
  color: #4e5969;
  border: none;
}

.btn-back:hover {
  background-color: #e5e6eb;
  color: #4e5969;
}

.btn-edit {
  background-color: #2783fb;
  border-color: #2783fb;
}

.btn-edit:hover {
  background-color: #1d72e3;
  border-color: #1d72e3;
}

.btn-delete {
  background-color: #f53f3f;
  border-color: #f53f3f;
}

.btn-delete:hover {
  background-color: #e03636;
  border-color: #e03636;
}

.btn-approve {
  background-color: #00b42a;
  border-color: #00b42a;
}

.btn-approve:hover {
  background-color: #00a824;
  border-color: #00a824;
}

.btn-reject {
  background-color: #f53f3f;
  border-color: #f53f3f;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .position-detail {
    padding: 10px;
  }

  .content-wrapper {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 16px;
  }

  .status-tag {
    margin-left: 0;
    margin-top: 10px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .action-buttons .el-button {
    flex: 1;
    min-width: 120px;
  }

  .label {
    width: 80px;
  }
}

@media (min-width: 1024px) {
  .detail-cards {
    grid-template-columns: 1fr 1fr;
  }
}
</style>